<template>
  <div class="loginIndex">
    <n-image
      height="100"
      preview-disabled
      src="https://ssc.homedo.com/static/png/logo2-90b2fe38.png"
    />
    <n-form
      class="loginForm"
      ref="formRef"
      :label-width="65"
      :model="formValue"
      :rules="rules"
      label-placement="left"
    >
      <n-form-item label="账号" path="account">
        <n-input v-model:value="formValue.account" placeholder="电话号码" />
      </n-form-item>
      <n-form-item label="验证码" path="code">
        <n-input v-model:value="formValue.code" placeholder="验证码" />
      </n-form-item>
      <n-form-item>
        <n-button attr-type="button" @click="handleValidateClick" color="#FF8300" :loading="loading" style="margin-right: 10px;">
          登录
        </n-button>
        <n-button attr-type="button" @click="goBack" color="#FF8300">
          返回
        </n-button>
      </n-form-item>
    </n-form>
    <n-divider title-placement="center"> 爱谱华顿一网统管平台 </n-divider>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useMessage } from 'naive-ui'
import { code, login, currentUser, getDDCode } from "@/apis/login/index.js";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import router from "@/router";

const message = useMessage()
const formRef = ref()
const formValue = ref({
  account: "18326907519",
  password: "",
  origin: "code",
  code: "006688",
  timestamp: "",
  client_id: "admin",
  client_secret: "123456",
  scope: "all",
  grant_type: "password",
})
const rules = {
  account: {
    required: true,
    message: '请输入电话号码',
    trigger: ['input']
  },
  code: {
    required: true,
    message: '请输入验证码',
    trigger: ['input']
  }
}
const loading = ref(false)
const  handleValidateClick = (e) => {
  e.preventDefault()
  formRef.value?.validate( async (errors) => {
    if (!errors) {
      const res = await login(formValue.value);
      if (res && res.token) {
        localStorage.setItem("token", res.token)
        await getCurrentUser()
      } else {
        window.electronAPI.send('showError', { title: '', content: res.msg })
      }
    }
    else {
      console.log(errors)
      message.error('Invalid')
    }
  })
}

const getCurrentUser = async () => {
  loading.value = true
  const res = await currentUser();
  console.log(res)
  if (res) {
    loading.value = false
    localStorage.setItem("userInfo", JSON.stringify(res.userInfo))
    message.success("登录成功")
    await router.push({ path: "/" })
    console.log(window.location.href)
  }
}
console.log(window.location.href)
const goBack = () => {
  router.go(-1)
}
</script>

<style scoped lang="scss">
.loginIndex {
  padding: 50px;
  border-radius: 10px;
}
.loginForm {
  margin-top: 30px;
}
:deep(.n-form-item .n-form-item-label) {
  color: #FFFFFF;
}
</style>
